/**
 *
 */
package jp.co.takapy.baycity.server.parser;

import java.util.ArrayList;
import java.util.List;


import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.nodes.RemarkNode;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.tags.TitleTag;
import org.htmlparser.util.EncodingChangeException;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

/**
 * @author Takapy
 *
 */
public class TimeTableParser {

    /**
     * コンストラクタ
     * @param url
     * @throws Exception
     */
    public TimeTableParser(String url) throws Exception {

        Parser.getConnectionManager().setRedirectionProcessingEnabled(true);
        Parser.getConnectionManager().setCookieProcessingEnabled(true);

        Parser parser = new Parser();

        // URLを指定
        parser.setResource(url);

        // 抽出対象を指定
        NodeFilter filter = null;
        // AndFilter, OrFilter, RegexFilter, etc...
        // filter = new TagNameFilter("A");
        //filter = new TagNameFilter("b");

        // パース(Tableタグごとに)
        try {
          parse(parser, filter);
        } catch (EncodingChangeException ece) {
          // Parser#reset した後でリトライすると適切なエンコーディングで処理してくれるらしい(未検証)
          ece.printStackTrace();
          parser.reset();
          parse(parser, filter);
        }
      }


    private String title;
    private List<String> text = new ArrayList<String>();
    private List<String> comment = new ArrayList<String>();
    private List<LinkTag> linktag = new ArrayList<LinkTag>();
    private List<ImageTag> imagetag = new ArrayList<ImageTag>();
    private List<TagNode> tag = new ArrayList<TagNode>();
    private List<TableTag> tabletag = new ArrayList<TableTag>();
    private List<TableRow> tableRows = new ArrayList<TableRow>();
    private List<TableColumn> tableColumns = new ArrayList<TableColumn>();


    private void parse(Parser parser, NodeFilter filter) throws ParserException {
        NodeList list = parser.parse(filter);
        NodeIterator i = list.elements();
        while (i.hasMoreNodes()) {
          analyze(i.nextNode());
        }
      }

      public String getId(String url) {

          //url文字列をuriとパラメータで分割
          String[] urlStrs = url.split("\\?");

          //パラメータ文字列ごとに分割
          String[] params = urlStrs[1].split("\\&");

          //ID文字列を切り出す
          String[] cdStrs = params[0].split("\\=");

          return cdStrs[1];
      }
      public String getTitle() {
        return title;
      }

      public String[] getTexts() {
        return (String[]) text.toArray(new String[text.size()]);
      }

      public String[] getComments() {
        return (String[]) comment.toArray(new String[comment.size()]);
      }

      public String[] getLinkUrls() {
        String[] urls = new String[linktag.size()];
        for (int i = 0; i < linktag.size(); i++) {
          urls[i] = linktag.get(i).getLink(); // 絶対URL
        }
        return urls;
      }

      public String[] getImageUrls() {
        String[] urls = new String[imagetag.size()];
        for (int i = 0; i < imagetag.size(); i++) {
          urls[i] = imagetag.get(i).getImageURL(); // 絶対URL
        }
        return urls;
      }

      public String[] getTags() {
        String[] tegs = new String[tag.size()];
        for (int i = 0; i < tag.size(); i++) {
          //tegs[i] = tag.get(i).toHtml();
          tegs[i] = tag.get(i).toString();
        }
        return tegs;
      }

      public String[] getDirection(String[] texts) {

          //行き先
          String[] dir = new String[2];
          //配列カウンタ用
          int cnt = 0;
          for (int i = 0; i < texts.length; i++) {

              if (texts[i].contains("行き")) {
                  String[] st = null;
                  st = texts[i].split(" ");
                  dir[cnt] = st[1];
                  cnt = cnt + 1;
              }
            }
          return dir;
      }

      public List<TableColumn> getTableElements() {

          //テーブル要素格納用配列
          String[] table = new String[1];

          //テーブルタグから行解析
          TableRow[] tableRow = tabletag.get(2).getRows();
          for (TableRow row : tableRow) {
              tableRows.add(row);
          }

          //行から列を解析
          for (int i =0; i < tableRows.size(); i++) {
              TableColumn[] tableColumn = tableRows.get(i).getColumns();
              for (TableColumn column : tableColumn) {
                  tableColumns.add(column);
              }
          }

          return tableColumns;
      }

      private void analyze(Node node) throws ParserException {

          //テキスト解析
          if (node instanceof TextNode) {
              text.add(((TextNode) node).getText());

          //Tableタグの解析
          } else if (node instanceof TableTag) {

                if (node instanceof TagNode) { // Tag

                  if (node instanceof TableTag) {
                    tabletag.add((TableTag) node);
                  }
                  tag.add((TagNode) node);
                }
          }

        // 再帰
        NodeList children = node.getChildren();
        if (children != null) {
          NodeIterator i = children.elements();
          while (i.hasMoreNodes())
            analyze(i.nextNode());
        }
      }
    }
